package com.da.javatest.niuke.baodian;

/**
 * @author chenlida
 * @date 2020/10/4 12:50
 * https://www.nowcoder.com/practice/b0850698cb41449188344cdb647f3e99?tpId=8&tqId=10994&rp=1&
 * ru=%2Fta%2Fcracking-the-coding-interview&qru=%2Fta%2Fcracking-the-coding-interview%2Fquestion-ranking
 */
public class C4Replacement {
    public String replaceSpace(String iniString, int length) {
        if (length < 1) {
            return iniString;
        }
        String[] s = iniString.split(" ", -1);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length - 1; i++) {
            sb.append(s[i]).append("%20");
        }
        sb.append(s[s.length - 1]);
        return sb.toString();
    }

    public String replaceSpace2(String str, int length) {
        if (str == null || str.length() == 0) {
            return str;
        }

        StringBuilder sb = new StringBuilder();
        for (char c : str.toCharArray()) {
            if (c != ' ') {
                sb.append(c);
            } else {
                sb.append("%20");
            }
        }

        return sb.toString();
    }
}
